import os
from pathlib import Path
from typing import Dict, Any

class Config:
    """基础配置类"""
    # 项目根目录
    BASE_DIR = Path(__file__).parent.parent
    
    # 数据库配置
    MYSQL_USER = "root"
    MYSQL_PASSWORD = "123456"
    MYSQL_HOST = "localhost"
    MYSQL_DATABASE = "llm_service"
    SQLALCHEMY_DATABASE_URI = None  # 将在初始化时设置
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    
    # LLM 服务配置
    DEEPSEEK_API_KEY = None
    DEEPSEEK_API_BASE = "https://api.deepseek.com"
    
    @classmethod
    def load_from_file(cls) -> Dict[str, Any]:
        """从文件加载配置"""
        config = {}
        
        # 尝试从 config.json 加载
        json_file = cls.BASE_DIR / 'config.json'
        if json_file.exists():
            import json
            with open(json_file) as f:
                config.update(json.load(f))
        
        # 尝试从 .env 加载
        env_file = cls.BASE_DIR / '.env'
        if env_file.exists():
            from dotenv import load_dotenv
            load_dotenv(env_file)
        
        # 从环境变量加载
        for key in dir(cls):
            if key.isupper():
                env_value = os.getenv(key)
                if env_value is not None:
                    config[key] = env_value
        
        return config
    
    @classmethod
    def init_app(cls, app):
        """初始化应用配置"""
        config = cls.load_from_file()
        
        # 更新配置值
        for key, value in config.items():
            if hasattr(cls, key):
                setattr(cls, key, value)
        
        # 设置数据库 URI
        cls.SQLALCHEMY_DATABASE_URI = (
            f"mysql+mysqlconnector://{cls.MYSQL_USER}:{cls.MYSQL_PASSWORD}"
            f"@{cls.MYSQL_HOST}/{cls.MYSQL_DATABASE}"
        )
        
        # 配置 Flask 应用
        app.config.from_object(cls)
        
        return app

class DevelopmentConfig(Config):
    """开发环境配置"""
    DEBUG = True

class TestingConfig(Config):
    """测试环境配置"""
    TESTING = True
    SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'

class ProductionConfig(Config):
    """生产环境配置"""
    DEBUG = False

# 配置映射
config = {
    'development': DevelopmentConfig,
    'testing': TestingConfig,
    'production': ProductionConfig,
    'default': DevelopmentConfig
} 